package com.liukai.novel_rack.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.liukai.novel_commons.Result;
import com.liukai.novel_commons.entities.NovelChapter;
import com.liukai.novel_commons.entities.NovelRack;
import com.liukai.novel_commons.utils.Constans;
import com.liukai.novel_commons.utils.FileUtil;
import com.liukai.novel_commons.utils.JSONUtil;
import com.liukai.novel_commons.utils.LogUtils;
import com.liukai.novel_commons.utils.State;
import com.liukai.novel_info.call_back.INovelCallBack;
import com.liukai.novel_info.presenter.impl.NovelPresenterImpl;
import com.liukai.novel_info.ui.ReadActivity;
import com.liukai.novel_rack.R;
import com.liukai.novel_rack.R2;
import com.liukai.novel_rack.adapter.NovelRackAdapter;
import com.liukai.novel_base.base.BaseFragment;
import com.liukai.novel_rack.call_back.IRackCallBack;
import com.liukai.novel_rack.presenter.impl.RackPresenterImpl;
import com.liukai.novel_rack.ui.SearchActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import cz.msebera.android.httpclient.Header;

public class NovelRackFragment extends BaseFragment implements IRackCallBack, INovelCallBack {

    private Context mContext;
    private RecyclerView mRecyclerView;
    private RackPresenterImpl mRackPresenterImpl;
    private String mUserId;
    private NovelRackAdapter mBookRackAdapter;
    private AsyncHttpClient mClient;
    private NovelPresenterImpl mNovelPresenter;

    @BindView(R2.id.toolbar)
    View toolbar;
    private View mBtnMore;
    private View mBtnSearch;


    /**
     * 获取Fragment的上下文
     *
     * @param view
     * @return
     */
    @Override
    protected Context getFragmentContext(View view) {
        mContext = view.getContext();
        return view.getContext();
    }

    /**
     * 绑定组件
     *
     * @param view
     */

    @Override
    protected void initView(View view) {
        super.initView(view);
        mBtnSearch = toolbar.findViewById(R.id.layout_search);
        mBtnMore = toolbar.findViewById(R.id.layout_more);
    }

    @Override
    protected void initDate(View view) {
        super.initDate(view);
        setUpState(State.SUCCESS);
        mClient = new AsyncHttpClient();
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRackPresenterImpl = new RackPresenterImpl();
        mRackPresenterImpl.registerCallback(this);
        mNovelPresenter = new NovelPresenterImpl();
        mNovelPresenter.registerCallback(this);
        if (Constans.getUserInfo() == null)
            return;
        mUserId = Constans.getUserInfo().getUserId();
        LogUtils.e(getClass(), "userInfo:" + Constans.getUserInfo());
        if (mUserId == null || mUserId.equals("")) {
            return;
        }
        mRackPresenterImpl.findAllRackByUserId(mUserId);
    }

    /**
     * 设置适配器
     */
    @Override
    protected void initAdapter(View view) {
        mBookRackAdapter = new NovelRackAdapter(view.getContext(), Constans.getNovelRackList());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(view.getContext());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mBookRackAdapter);

        // 书架中小说点击事件监听
        mBookRackAdapter.setOnNovelListener(new NovelRackAdapter.OnNovelListener() {
            @Override
            public void onNovelClickListener(NovelRack novelRack) {
                mRackPresenterImpl.loadMuLu(novelRack.getNovelId());
                Toast.makeText(mContext, "novelRack:" + novelRack.getNovelId(), Toast.LENGTH_SHORT).show();
                Integer chapterId = novelRack.getRecentlyChapter();
                if (chapterId == 0)
                    chapterId += 1;
                final String path = Constans.FILE_PATH + novelRack.getNovelId() + "-" + chapterId + ".txt";
                File file = new File(path);
                if (file.exists()) {
                    Intent intent = new Intent(mContext, ReadActivity.class);
                    intent.putExtra("novelId", novelRack.getNovelId());
                    intent.putExtra("recentChapter", novelRack.getRecentlyChapter());
                    intent.putExtra("filePath", path);
//                    startActivityForResult(intent,Constans.CODE_REQUEST_NovelRackFragment);
                    startActivity(intent);
                } else {
                    mNovelPresenter.findNovelChapterById(novelRack.getNovelId(), novelRack.getRecentlyChapter());
                }
            }

            @Override
            public void onNovelLongClickListener(NovelRack novelRack, View view) {
                myPopupMenu(novelRack,view);
            }
        });

        mBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "搜索", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(mContext, SearchActivity.class));
            }
        });

        mBtnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "更多", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取布局的ID
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_novel_rack;
    }

    private void myPopupMenu(final NovelRack novelRack, View v) {
        //定义PopupMenu对象
        PopupMenu popupMenu = new PopupMenu(mContext, v, Gravity.RIGHT);
        //设置PopupMenu对象的布局
        popupMenu.getMenuInflater().inflate(R.menu.rack_menu, popupMenu.getMenu());
        //设置PopupMenu的点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.delete){
                    mRackPresenterImpl.deleteRackById(novelRack);
                }
                return true;
            }
        });
        //显示菜单
        popupMenu.show();
    }

    /**
     * 返回用户的书架信息
     *
     * @param result
     */
    @Override
    public void findAllRackByUserIdResult(Result result) {
        if (result.getCode() != 200)
            return;
        // 解析后台传回来的书架信息
        List<NovelRack> novelRackList = JSONUtil.resolverResultList(result, NovelRack.class);
        mBookRackAdapter.setNovelRacks(novelRackList);

        LogUtils.e(getClass(), "result:" + result.toString());
        for (NovelRack novelRack : novelRackList) {
            LogUtils.e(getClass(), "novelRack:" + novelRack.toString());
        }

    }

    @Override
    public void loadMuLuResult(Result result) {
        if (result.getCode() != 200) return;
        List<NovelChapter> novelChapters = JSONUtil.resolverResultList(result, NovelChapter.class);
        Constans.setMuluChapter(novelChapters);

    }

    @Override
    public void deleteRackById(Result result) {
        Toast.makeText(mContext, result.getMsg(), Toast.LENGTH_SHORT).show();
        if (result.getCode() == 200){
            mRackPresenterImpl.findAllRackByUserId(Constans.getUserInfo().getUserId());
        }
    }

    @Override
    public void findNovelByIdResult(Result result) {

    }

    @Override
    public void findNovelChapterByIdResult(Result result) {
        LogUtils.e(getClass(), "result:" + result.toString());

        NovelChapter novelChapter = JSONUtil.resolverResult(result, NovelChapter.class);
        String filePath = Constans.FILE_PATH + novelChapter.getNovelId() + "-" + novelChapter.getChapterId() + ".txt";
        String filePath1 = FileUtil.stringToFile(filePath, novelChapter);

        LogUtils.e(getClass(), "filePath1:" + filePath1);

        Intent intent = new Intent(mContext, ReadActivity.class);
        intent.putExtra("novelId", novelChapter.getNovelId());
        intent.putExtra("chapterId", novelChapter.getChapterId());
        intent.putExtra("filePath", filePath1);
        intent.putExtra("chapterName", novelChapter.getChapterName());

//        startActivityForResult(intent,Constans.CODE_REQUEST_NovelRackFragment);
        startActivity(intent);

    }


}
